package com.szholly.pro.watergas_server.ps.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.pro.watergas_server.common.web.BaseController;
import com.szholly.pro.watergas_server.common.web.RequestUnit;
import com.szholly.pro.watergas_server.ps.service.DataModificationService;
import com.szholly.pro.watergas_server.ps.service.DataReportService;
import com.szholly.pro.watergas_server.ps.service.OnlineMonitorService;
import com.szholly.pro.watergas_server.ps.service.RemoteService;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.PageInfo;
import com.szholly.data.general.RowBase;
import com.szholly.plug.form.excel.utils.StringUtil;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/DataModification/*")
public class DataModificationController extends BaseController {

	@Autowired
	DataModificationService dataModificationService;

	@Autowired
	OnlineMonitorService onlineMonitorService;
	
	@Autowired
	DataReportService dataReportService;
	
	@Autowired
	RemoteService remoteService;
	
	/**
	 * 修约数据
	 * gislin
	 * 2016年6月27日
	 * @throws ParseException 
	 */
	@RequestMapping(value = "/modifyData")
	public void modifyData(HttpServletRequest resq, HttpServletResponse res) throws ParseException{
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String mn = RequestUnit.getString("mn");
		String qn = RequestUnit.getString("qn");
		String datatimeStr = RequestUnit.getString("datatime");
		String userId = RequestUnit.getString("userId");
		String dataSource = RequestUnit.getString("dataSource");
		String newData = RequestUnit.getString("newData");
		String dataFlag = RequestUnit.getString("dataFlag");
		String certificateId = RequestUnit.getString("certificateId");
		String WATER_TYPE=RequestUnit.getString("WATER_TYPE");
		if(qn.contains(",")&&datatimeStr.contains(",")){
			String[] qnArr=qn.split(",");
			String[] datatimeArr=datatimeStr.split(",");
			String qnStr="";
			String datatimes="";
			for(int i=0;i<qnArr.length;i++){
				qnStr=qnArr[i].toString();
				datatimes=datatimeArr[i].toString();
				dataModificationService.modifyData(mn, qnStr, datatimes, dataSource, newData, dataFlag, userId,certificateId,WATER_TYPE);
			}
		}
		else{
			dataModificationService.modifyData(mn, qn, datatimeStr, dataSource, newData, dataFlag, userId,certificateId,WATER_TYPE);	
		}
		outSuccessString();
	}
	
	/**
	 * 获取凭证数据
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getCertificateInfo")
	public void getCertificateInfo(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = new HashMap<String,String>();
		String certificate_id = RequestUnit.getParameter("CERTIFICATE_ID");
		RowBase certificate = dataModificationService.getCertificate(certificate_id);
		params.put("certificate_id", certificate_id);
		List<RowBase> list = dataModificationService.getCertificateFileList(params);
		HashMap<String, Object> result = new HashMap<>();
		result.put("certificate", certificate);
		result.put("certificate_file", list);
		JSONObject jsonObj = JSONObject.fromObject(result);
		outString(jsonObj.toString());
	}

	/**
	 * 获取未修约数据
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getNotModifyData")
	public void getNotModifyData(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();
		PageInfo pageInfo = DataUtil.getPageInfo();
		List<RowBase> list = dataModificationService.getNotModifyDataList(params, pageInfo);
		String result = DataUtil.listToJSONObject(list, null, pageInfo).toString();
		outString(result);
	}
	
	/**
	 * 获取已经修约的数据
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getModifiedData")
	public void getModifiedData(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();
		PageInfo pageInfo = DataUtil.getPageInfo();

		List<RowBase> list = dataModificationService.getModifiedDataList(params, pageInfo);
		String result = DataUtil.listToJSONObject(list, null, pageInfo).toString();
		outString(result);
	}
	
	/**
	 * 获取凭证数据
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getCertificateDataList")
	public void getCertificateDataList(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();
		PageInfo pageInfo = DataUtil.getPageInfo();

		List<RowBase> list = dataModificationService.getCertificateList(params, pageInfo);
		String result = DataUtil.listToJSONObject(list, null, pageInfo).toString();
		outString(result);
	}
	
	/**
	 * 获取凭证数据
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getCertificateFileList")
	public void getCertificateFileList(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = new HashMap<String,String>();
		String certificate_id = RequestUnit.getParameter("CERTIFICATE_ID");
		params.put("certificate_id", certificate_id);
		List<RowBase> list = dataModificationService.getCertificateFileList(params);
		String result = DataUtil.listToJSONObject(list).toString();
		outString(result);
	}
	
	/**
	 * 保存修约数据
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateModifiedData")
	public void updateModifiedData(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();
		int r = dataModificationService.updateModifiedData(params);
		outString("{\"data\":\"success\",\"rowcount\":\""+r+"\"}");
	}
	/**
	 * 保存凭证信息
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveCertificate")
	public void saveCertificate(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		 String guid=RequestUnit.getParameter("GUID");
		 HashMap<String, Object> parms = RequestUnit.getHashMapParmO();
		 String sql = "select * from Monitor_Data_Certificate order by CREATE_TIME desc ";
		 JSONObject json = new JSONObject();
		 try{
			 //如果有guid直接更新凭证表信息
			 if(StringUtil.IsNotNullOrEmpty(guid)){
				 DataUtil.Update("monitor_data_certificate", parms); 
				 json.put("GUID", guid);
			 }
		 else{//没有guid新增凭证信息
			 DataUtil.Create("monitor_data_certificate", parms);
			 List<GlobalParameter> parm = new ArrayList<>();
			 List<RowBase> list = DataUtil.getSelectRows(sql, parm);
			 if(list.size()>0){
				 RowBase r=list.get(0);
				 json.put("GUID", r.getValue("GUID"));
			 }
		  } 
			outString(json.toString());
		 } catch(Exception e){
				String msg = e.getMessage();
				outString(msg);
			}
	}
	
	/**
	 * 保存凭证文件
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveCertificateFileList")
	public void saveCertificateList(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = new HashMap<String,String>();
		String certificate_id = RequestUnit.getParameter("CERTIFICATE_ID");
		String files = RequestUnit.getParameter("FILES");
		
		params.put("certificate_id", certificate_id);
		params.put("files", files);
		int r = dataModificationService.saveCertificateFile(params);
		 //上传凭证并关联数据，使得修约有效
		 String MN = RequestUnit.getParameter("MN");
		 String modifyDate = RequestUnit.getParameter("MODIFY_DATE");
		 String GUID = RequestUnit.getParameter("GUID");
		 String tableFlag = RequestUnit.getParameter("dataSource");
		 dataModificationService.updateModifiedDataCerfifyId(tableFlag,certificate_id,GUID,MN,modifyDate);
		outString("{\"data\":\"success\",\"rowcount\":\""+r+"\"}");
	}
	
	/**
	 * 更新修约数据modify_certificate_id
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateModifiedCerticateId")
	public void updateModifiedCerticateId(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		 String certificate_id = RequestUnit.getParameter("CERTIFICATE_ID");
		 String MN = RequestUnit.getParameter("MN");
		 String modifyDate = RequestUnit.getParameter("MODIFY_DATE");
		 String tableFlag = RequestUnit.getParameter("dataSource");
		 int r = dataModificationService.updateModifiedCerticateIdToNull(tableFlag,certificate_id,MN,modifyDate);
		outString("{\"data\":\"success\",\"rowcount\":\""+r+"\"}");
	}
	
	/**
	 * 更新修约数据的凭证
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateModifyDataCert")
	public void updateModifyDataCert(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();
		int r = dataModificationService.updateModifyDataCert(params);
		outString("{\"data\":\"success\",\"rowcount\":\""+r+"\"}");
	}
	
	/**
	 * 根据凭证ID，获取关联的修约数据
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getModifyDataCountByCertificate")
	public void getModifyDataCountByCertificate(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = new HashMap<String,String>();
		String certificate_id = RequestUnit.getParameter("CERTIFICATE_ID");
		if(StringUtil.IsNotNullOrEmpty(certificate_id)){
			params.put("certificate_id", certificate_id);
		}
		
		int r = dataModificationService.getModifyDataCountByCertificate(params);
		
		outString("{\"data\":\"success\",\"rowcount\":\""+r+"\"}");
	}
	
	@RequestMapping(value = "/deleteCertificate")
	public void deleteCertificate(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = new HashMap<String,String>();
		String certificate_id = RequestUnit.getParameter("CERTIFICATE_ID");
		if(StringUtil.IsNotNullOrEmpty(certificate_id)){
			params.put("certificate_id", certificate_id);
		}
		
		boolean r = dataModificationService.deleteCertificate(params);
		if(r){
			outString("{\"data\":\"success\"}");
		}else{
			outString("{\"data\":\"failure\"}");
		}
	}
	
	@RequestMapping(value = "/deleteCertificateFile")
	public void deleteCertificateFile(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		String guid = RequestUnit.getParameter("GUID");
		boolean r = dataModificationService.deleteCertificateFile(guid);
		if(r){
			outString("{\"data\":\"success\"}");
		}else{
			outString("{\"data\":\"failure\"}");
		}
	}
	/**
	 * 根据站点，凭证上传状态，时间来查询站点的已修约数据的凭证上传数据。
	 * @param resq
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value = "/getModifiedRecordByCertifyStatus")
	public void getModifiedRecordByCertifyStatus(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		Map<String, String> params = getParams();
		PageInfo pageInfo = DataUtil.getPageInfo();
		List<RowBase> list = dataModificationService.getAllModifiedDataList(params, pageInfo);
		String result = DataUtil.listToJSONObject(list, null, pageInfo).toString();
		outString(result);
	}
	private Map<String, String> getParams() {
		Map<String, String> map = new HashMap<String, String>();

		String start = RequestUnit.getParameter("START");
		if (StringUtil.IsNotNullOrEmpty(start)) {
			map.put("start", start);
		}
		String end = RequestUnit.getParameter("END");
		if (StringUtil.IsNotNullOrEmpty(end)) {
			map.put("end", end);
		}

		String mn = RequestUnit.getParameter("MN");
		if (StringUtil.IsNotNullOrEmpty(mn)) {
			map.put("mn", mn);
		}
		
		String tableFlag = RequestUnit.getParameter("TABLE_FLAG");
		if (StringUtil.IsNotNullOrEmpty(tableFlag)) {
			map.put("tableFlag", tableFlag);
		}

		if (StringUtil.IsNullOrEmpty(mn)) {
			String wwtp_id = RequestUnit.getParameter("WWTP_ID");
			String flow_type = RequestUnit.getParameter("FLOW_TYPE");
			String station_id = RequestUnit.getParameter("STATION_ID");
			mn = onlineMonitorService.getDataCollectionInstrumentNo(wwtp_id, flow_type, station_id);
			if (mn != null) {
				map.put("mn", mn);
			}
		}
		
		String data_times = RequestUnit.getParameter("DATA_TIMES");
		if (StringUtil.IsNotNullOrEmpty(data_times)) {
			map.put("data_times", data_times);
		}
		
		String modify_method = RequestUnit.getParameter("MODIFY_METHOD");
		if (StringUtil.IsNotNullOrEmpty(modify_method)) {
			map.put("modify_method", modify_method);
		}
		
		String hasCertificate = RequestUnit.getParameter("HAS_CERTIFICATE");
		if (StringUtil.IsNotNullOrEmpty(hasCertificate)) {
			map.put("modify_certificate", "1");
		}
		
		String certificate_id = RequestUnit.getParameter("CERTIFICATE_ID");
		if (StringUtil.IsNotNullOrEmpty(certificate_id)) {
			map.put("certificate_id", certificate_id);
		}
		
		String P011AVG = RequestUnit.getParameter("P011_B");
		if (StringUtil.IsNotNullOrEmpty(P011AVG)) {
			map.put("P011AVG", P011AVG);
		}
		String PB01AVG = RequestUnit.getParameter("PB01_B");
		if (StringUtil.IsNotNullOrEmpty(PB01AVG)) {
			map.put("PB01AVG", PB01AVG);
		}
		String P060AVG = RequestUnit.getParameter("P060_B");
		if (StringUtil.IsNotNullOrEmpty(P060AVG)) {
			map.put("P060AVG", P060AVG);
		}
		String WATER_TYPE = RequestUnit.getParameter("WATER_TYPE");
		if (StringUtil.IsNotNullOrEmpty(WATER_TYPE)) {
			map.put("WATER_TYPE", WATER_TYPE);
		}
		return map;
	}
	/**
	 * 远程获取小时数据
	 * wangl
	 */
	@RequestMapping(value = "/getRemoteHourData")
	public void getRemoteHourData(HttpServletRequest resq, HttpServletResponse res) throws Exception {
		String mn = RequestUnit.getParameter("mn");
		String cn = RequestUnit.getParameter("cn");
		String remoteST = RequestUnit.getParameter("remoteST");
		String remoteET = RequestUnit.getParameter("remoteET");
		String cp = "BeginTime="+remoteST+",EndTime="+remoteET;
		remoteService.sendOrder( mn, cn, cp,0,"小时数据远程获取");
		outString("{\"data\":\"success\"}");
	}
}
